/**
 * xqx,2023.07.19
 * 前端翻译模块
 * 模块translate是layui扩展模块
 */
layui.define(['translate'], function(exports) {
    var translate = layui.translate;
    translate.selectLanguageTag.show = false; //不出现的select的选择语言
    translate.language.setLocal('english');

    var homeTranslate = {
        execute: function(){
            xy_translate_page();
        },
        //直接将英语翻译成目标语言，主要用于提示信息的翻译
        trans_info: function(text){
            var to = sessionStorage.getItem("toLang");  //目标语言
            var search = homelangsDict[to][homelangsDict['en'].indexOf(text)];
            if(search && search.trim() !=''){
                return search;
            }else{
                return text;
            }
        }
    };

    /** 进行文字替换形式翻译页面 start */
    /**
     * 2023.07.17  xqx
     * 翻译页面
     */
    function xy_translate_page(){
        console.log('lang: ',sessionStorage.getItem("fromLang") ,' => ', sessionStorage.getItem("toLang"));
        console.log(location.pathname)
        if(sessionStorage.getItem("fromLang") == sessionStorage.getItem("toLang")){
            return;
        }
        var text = '';
        //button
        $('button').each(function(i,n){
            $(this).text(xy_translate_word($(this).text()));
        });
        $('button').addClass('ignore'); //添加class='ignore'，layui自动翻译组件将对该元素不进行翻译

        //表单验证的提示信息
        $(':input[lay-reqText]').each(function(i,n){
            $(this).attr('lay-reqText',xy_translate_word($(this).attr('lay-reqText')));
        });

        //对页面进行翻译
        //HTML标题
        text = $('title').text();
        $('title').text().split('-').forEach(element => {
            text = text.replace(element.trim(),xy_translate_word(element.trim()));
        });
        $('title').text(text);
        $('title').addClass('ignore');
        // app-box标题
        $('.app-box .navbar .navbar-center').html(xy_translate_word($('.app-box .navbar .navbar-center')));

        // 评论模块，由于加载顺序，需延迟翻译
        setTimeout(() => {
            $('.comments-container .total span:first').html(xy_translate_word($('.comments-container .total span:first')));
        }, 2000);
        
        
        
        /** Include start */
        // Include/header_xy.html  pc header
        $('#chj-header a').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        $('.m-header-panel .m-menu-select-title').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        $('#chj-header').addClass('ignore');

        // Include/langs.html
        $('#langActionsheet .weui-actionsheet__title-text').html(xy_translate_word($('#langActionsheet .weui-actionsheet__title-text')));
        $('#langActionsheet #langActionsheetCancel').html(xy_translate_word($('#langActionsheet #langActionsheetCancel')));
        $('#langActionsheet').addClass('ignore');

        // Include/footer.html
        $('.xy-footer .xy-footer-box a').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        $('.xy-footer').addClass('ignore');

        /** Include end */

        var moudle = location.pathname.split('/')[2];
        switch (moudle) {
            case 'article':
                trans_article();
                break;
            case 'feedback':
                trans_feedback();
                break;
            case 'goods':
                trans_goods();
                break;
            case undefined:
            case 'index':
                trans_index();
                break;
            case 'order':
                trans_order();
                break;
            case 'service':
                trans_service();
                break;
            case 'user':
                trans_user();
                break;
            default:
                break;
        }
        

        //layui自动翻译组件
        var langArr = {
            'zh' : 'chinese_simplified',
            'en' : 'english',
            'spa' : 'spanish',
            'de' : 'german',
            'ara' : 'arabic'
        };
        // translate.changeLanguage(langArr[sessionStorage.getItem("toLang")]);

    }

    function trans_article(){
        console.log('article.....')
        // $('.app-box .xy-article').addClass('ignore');
        // 作者、时间
        let elemArr = ['.xy-article-author-name', '.xy-article-author-time'];
        elemArr.forEach(function(i,n){
            $(i).each(function(ii,nn){
                let t = $(this).html().split(":")[0].trim();
                $(this).html($(this).html().replace(t,xy_translate_word(t)));
            });
        });

        // 弹出菜单
        $('#actionsheet .selectAction').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        $('#actionsheetCancel').html(xy_translate_word($('#actionsheetCancel')));

        // edit.html
        $('.app-box .xy-form-box').addClass('ignore');
        $('.app-box .xy-form-box .layui-form-label').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

    }

    function trans_feedback(){
        $('.layout').addClass('ignore');
    }

    function trans_goods(){
        console.log('trans_goods.....')
        $('.app-box').addClass('ignore');
        // my.html
        $('.agency-country').each(function(i,n){
            let t = $(this).text().split(':')[0].trim();
            $(this).html($(this).html().replace(t,xy_translate_word(t)));
        });
        $('.agency-param').each(function(i,n){
            let t = $(this).text().split(':')[0].trim();
            $(this).html($(this).html().replace(t,xy_translate_word(t)));
        });
        $('.weui-btn').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        $('.weui-half-screen-dialog__title').html(xy_translate_word($('.weui-half-screen-dialog__title')));
        $('.layui-form-label').each(function(i,n){
            let t = $(this).text().split(':')[0].trim();
            $(this).html($(this).html().replace(t,xy_translate_word(t)));
        });
        // main.html
        $('.goods-menu .ucenter-menu').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        $('.del-box .layui-btn').html(xy_translate_word($('.del-box .layui-btn')));
        // article.html
        $('.navbar-center').each(function(i,n){
            if($(this).text().includes('-')){
                let t = $(this).text().split('-')[0].trim();
                $(this).html($(this).html().replace(t,xy_translate_word(t)));
            }
        });

        // show.html
        $('.container').addClass('ignore');
        xy_trans_elems(['.layui-breadcrumb a','.layui-table th','.layui-table td','.hhq-title','.goods-detail-btn','.sku-option-title']);
        // detail.html
        xy_trans_elems(['sku-option-title','.sku-option-items .option-item','.hhq-title span','.hhq-title a','#submit-order']);
        // submit_next.html
        xy_trans_elems(['.order-title','.hhq-submit']);

    }

    function trans_index(){
        //my.html
        //未登录
        $('.xy-main .hhq-box .hhq-title').html(xy_translate_word($('.xy-main .hhq-box .hhq-title')));

        //登录后
        // $('.xy-main .user-detail .user-name span:last').text(xy_translate_word($('.xy-main .user-detail .user-name span:first')));
        $('.xy-main .user-detail .user-name span:last').addClass('ignore');
        $('.xy-main .ucenter-menu').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
        //按钮
        $('.xy-main .weui-btn').each(function(i,n){
            text = $(this).text();
            text.split('/').forEach(element => {
                text = text.replace(element.trim(),xy_translate_word(element.trim()));
            });
            $(this).text(text);
        });

        // index.html
        $('.product-buttonlist a').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

    }

    function trans_order(){
        console.log('trans_order.....')
        $('.app-box').addClass('ignore');
        // my.html
        $('.status').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

        $('.order-box .order-item .order-info .order-param-title').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

        $('.order-box .order-item .order-info .order-param-value').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

        $('.order-box .order-item .order-time').each(function(i,n){
            let t = $(this).text().split(':')[0].trim();
            $(this).html($(this).html().replace(t,xy_translate_word(t)));
        });

        // my_detail.html
        xy_trans_elems(['.del-box .layui-btn','.order-title','tr th']);

        $('.agency-country').each(function(i,n){
            let t = $(this).text().split(':')[0].trim();
            $(this).html($(this).html().replace(t,xy_translate_word(t)));
        });

        $('.agency-param').each(function(i,n){
            let t = $(this).text().split(':')[0].trim();
            $(this).html($(this).html().replace(t,xy_translate_word(t)));
        });

        $('#products tr td:first-child').each(function(i,n){
            let _this = this;
            let t = $(_this).text().split(':')[0].trim();
            if(t.includes('*')){
                t.split('*').forEach(function(v,ii){
                    $(_this).html($(_this).html().replace(v.trim(),xy_translate_word(v.trim())));
                });
            }else{
                $(_this).html($(_this).html().replace(t,xy_translate_word(t)));
            }
        });

        // detail.html
        xy_trans_elems(['.goods-type','.layui-breadcrumb a']);

    }

    function trans_service(){
        // service 下面几个页面的标题
        
        // setting.html
        $('.app-box .setting-menu').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

        //feedback.html内容不翻译，在页面添加ignore了
        // about.html
        $('.app-box .xy-article').addClass('ignore');
        let elemArr = ['.xy-article-author-name', '.xy-article-author-time'];
        elemArr.forEach(function(i,n){
            $(i).each(function(ii,nn){
                let t = $(this).html().split(":")[0].trim();
                $(this).html($(this).html().replace(t,xy_translate_word(t)));
            });
        });

    }

    function trans_user(){
        // login.html  register.html  findpwd.html
        $('.box-left .action-title').each(function(i,n){
            $(this).html($(this).html().replace('Huben','<span class="ignore">Huben</span>'));
        });
        
        $('.box-left .action-btn').html(xy_translate_word($('.box-left .action-btn')));
        $('.loginBox .loginForm li').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

        $('.loginBox .loginForm label').each(function(i,n){
            var text = $(this).text();
            $(this).text().split('/').forEach(element => {
                text = text.replace(element.trim(),xy_translate_word(element.trim()));
            });
            $(this).text(text);
        });
        $('.loginBox .loginForm .xy-form-bottom a').html(xy_translate_word($('.loginBox .loginForm .xy-form-bottom a')));
        $('.loginBox .loginForm').addClass('ignore');

        // personal.html
        $('#change-nickname .weui-half-screen-dialog__title').html(xy_translate_word($('#change-nickname .weui-half-screen-dialog__title')));
        $('#change-nickname .layui-form-label').html(xy_translate_word($('#change-nickname .layui-form-label')));
        $('.app-box .weui-cell__bd').html(xy_translate_word($('.app-box .weui-cell__bd')));
        // $('#change-nickname').addClass('ignore');

        // repwd.html
        $('.xy-form-box .layui-form-label').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });
    }

    function xy_trans_elems(elems){
        elems.forEach(elem => {
            $(elem).each(function(i,n){
                $(this).html(xy_translate_word($(this)));
            });
        });
        
    }

    /**
     * 翻译  2023.07.17  xuqixiang
     * @param {*} elem 文本或文本所在的元素
     * @returns 返回翻译结果
     */
    function xy_translate_word(elem){
        if(!elem){
            return '';
        }
        var from = sessionStorage.getItem("fromLang"),  //原来语言
            to = sessionStorage.getItem("toLang");  //目标语言
        if(typeof(elem)=='string'){
            return find_text(from, to, elem);
        }else{
            return find_elem(from, to, elem);
        }
    }

    /**
     * 翻译元素内的文本  2023.07.27  xuqixiang
     * @param {*} from 源语言
     * @param {*} to 目标语言
     * @param {*} elem 文本所在的元素
     * @returns html
     */
    function find_elem(from, to, elem){
        var text = handleStr(elem.text()).trim();
        if(text != ''){
            var search = homelangsDict[to][homelangsDict[from].indexOf(text)];
            if(search && search.trim() !=''){
                return elem.html().replace(text, search);
            }else{
                return elem.html();
            }
        }else{
            return elem.html();
        }
        
    }

    /**
     * 翻译文本  2023.07.27  xuqixiang
     * @param {*} from 源语言
     * @param {*} to 目标语言
     * @param {*} text 文本
     * @returns 翻译后的文本
     */
    function find_text(from, to, text){
        var temp = handleStr(text).trim();
        if(temp != ''){
            var search = homelangsDict[to][homelangsDict[from].indexOf(temp)];
            if(search && search.trim() !=''){
                return text.replace(temp, search);
            }else{
                return text;
            }
        }else{
            return text;
        }
        
    }

    // 去除标点符号
    function handleStr(str) {
        return str.replace(/[\?:：]/g, '');
      }
      
    exports('homeTranslate', homeTranslate); //对外接口
});